﻿using SaaS.Core;
using SaaS.Model.Entity.Blogs;
using SaaS.Model.Enums;
using SaaS.Model.Dto.Blogs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using XCore.Dapper;
using XCore.Logger;
using XCore.Dependency;

namespace Web.System.Services.Blogs
{
    public class ArticleAppService : SystemApplicationServiceBase, ITransientDependency
    {
        public int Save(ArticleInput input)
        {
            string tagString = string.Join(",", input.Tags);
            if (input.Id.HasValue)
            {
                if (Repository.Update<Article, ArticleInput>(input))
                    this.SaveVersion(input.Id.Value);
                return input.Id.Value;
            }
            else
            {
                var entity = ObjectMapper.Map<Article>(input);
                entity.TagString = tagString;
                return Repository.InsertAndGetId(entity);
            }
        }
        public bool Delete(int id)
        {
            if (SDC.Articles.Any(c => c.Id == id && c.Status == ArticleStatus.Published)) throw new MessageException("发布状态，不可删除", (int)LogSource.Logic);
            return Repository.Delete<Article>(id);
        }
        public bool Reply(ArticleMessageInput input)
        {
            var entity = ObjectMapper.Map<ArticleMessage>(input);
            return Repository.Insert(entity);
        }
        /// <summary>
        /// 保存文章版本
        /// </summary>
        /// <param name="id"></param>
        private void SaveVersion(int id)
        {
            var content = SDC.Articles.Where(c => c.Id == id).Select(c => c.Content).FirstOrDefault();
            ArticleVersions article = new ArticleVersions { Content = content, ArticleId = id };
            Repository.Insert(article);
        }

        public int SaveTag(string name)
        {
            if (SDC.ArticleTags.Any(c => c.Name == name)) throw new MessageException("已存在相同标签", (int)LogSource.Business);
            ArticleTag tag = new ArticleTag { Name = name };
            return Repository.InsertAndGetId(tag);
        }
        public bool DeleteTag(string name)
        {
            return Repository.Delete<ArticleTag>(c => c.Name == name);
        }
    }
}
